var express = require('express');
var router = express.Router();
const SMSClient = require("@alicloud/sms-sdk");
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

const {userModel} = require("../db/index")

router.post('/login',async function(req,res,next){
    let {username,password,phone} = req.body;
    console.log(username,password,phone)
    if(username){
        let user = await userModel.findOne({username,password})
        if(user){
            res.send({code:200,msg:"登录成功",data:user}) 
        }else{
            res.send({code:400,msg:"登录失败"})
        }
    }else{
        let user = await userModel.findOne({phone})
        if(user){
            res.send({code:200,msg:"登录成功",data:user}) 
        }
        else{
            res.send({code:400,msg:"登录失败"}) 
        }
    }
})

router.post('/register',async function(req,res,next){
    let {username,password,phone} = req.body;
    let user = await userModel.findOne({username}) 
})

const accessKeyId = "LTAI5t84kUFyT3ugLZNkPuHw"; // 替换为你的 AccessKey ID
const secretAccessKey = "ooeBxbdw1VsvnWVxb6YVQwQksTct5C"; // 替换为你的 AccessKey Secret
const smsClient = new SMSClient({ accessKeyId, secretAccessKey });
// 发送短信验证码的接口
router.post("/code", async (req, res) => {
  let { phone } = req.body;

  if (!phone) {
    return res.status(400).json({ success: false, message: "手机号不能为空" });
  }
  // 生成随机验证码
  const code = Math.floor(100000 + Math.random() * 900000).toString();
  try {
    // 调用阿里云短信服务
    const result = await smsClient.sendSMS({
      PhoneNumbers: phone, // 目标手机号
      SignName: "阿里云短信测试", // 短信签名（需与阿里云控制台一致）
      TemplateCode: "SMS_154950909", // 短信模板CODE（需与阿里云控制台一致）
      TemplateParam: `{"code":"${code}"}`, // 短信模板中的变量
    });
    console.log("阿里云返回结果:", JSON.stringify(result, null, 2)); // 打印阿里云返回的结果
    if (result.Code === "OK") {
      // 验证码发送成功
      console.log(`验证码已发送至 ${phone}，验证码为：${code}`);
      res.send({ success: true, message: "验证码发送成功",code:code });//将生成的验证码返回给前端
    } else {
      // 发送失败
      console.error("短信发送失败:", result.Message);
      res.status(500).json({
        success: false,
        message: "短信发送失败",
        error: result.Message,
      });
    }
  } catch (error) {
    console.error("短信服务异常:", error.message);
    res.json({ success: false, message: "验证码发送失败", })//返回给前端错误
    res .status(500)  .json({ success: false, message: "短信服务异常", error: error.message });
  }
});

module.exports = router;
